/**
 * 
 */
package com.blog.oauth2;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSONObject;
import com.blog.core.http.HttpResult;
import com.blog.core.http.HttpStatus;
import com.blog.pojo.SysUser;
import com.blog.pojo.SysUserToken;
import com.blog.service.SysUserService;
import com.blog.service.SysUserTokenService;

/**
 * @author zyj
 *
 */
public class OAuth2Filter extends AuthenticatingFilter {
	
	@Autowired
	private SysUserTokenService sysUserTokenService;
	
	@Autowired
	private SysUserService sysUserService;

	@Override
	protected AuthenticationToken createToken(ServletRequest requset, ServletResponse response) throws Exception {
		//获取请求的token
		String token = getRequestToken((HttpServletRequest)requset);
		if(StringUtils.isBlank(token)) {
			return null;
		}
		return new JWTToken(token);
	}
	
	@Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return false;
    }
	
	@Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json; charset=utf-8");
        try {
            // 处理登录失败的异常
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            HttpResult result = HttpResult.error(HttpStatus.SC_UNAUTHORIZED, throwable.getMessage());
            String json = JSONObject.toJSONString(result);
            httpResponse.getWriter().print(json);
        } catch (IOException e1) {
        }
        return false;
    }

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		// 获取请求token，如果token不存在，直接返回401
        String token = getRequestToken((HttpServletRequest) request);
        if(StringUtils.isBlank(token)){
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            HttpResult result = HttpResult.error(HttpStatus.SC_UNAUTHORIZED, "invalid token");
            String json = JSONObject.toJSONString(result);
            httpResponse.getWriter().print(json);
            return false;
        }
        boolean flag = executeLogin(request, response);
        return flag;
	}
	
//	@Override
//    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
//    	String token = getRequestToken((HttpServletRequest) request);
//        SysUserToken userToken = sysUserTokenService.findByToken(token);
//        if (null != userToken) {
//	        Date expireTime = userToken.getExpireTime();
//	        if(expireTime.getTime()>System.currentTimeMillis()) {
//	        	SysUser user = sysUserService.get(userToken.getUserId());
//	        	if(user != null) {
//	        		return true;
//	        	}
//	        }
//        }
//        return false;
//    }
	
	private String getRequestToken(HttpServletRequest httpRequset) {
		//从header中获取token
		String token = httpRequset.getHeader("token");
		// 如果header中不存在token，则从参数中获取token
		if(StringUtils.isBlank(token)) {
			token = httpRequset.getParameter("token");
		}
		return token;
	}

}
